﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Spider_Demo.Common
{
    public class HttpHelper
    {
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="url">文件下载地址</param>
        /// <param name="filename">文件名称</param>
        /// <param name="path">文件保存路径</param>
        internal static string SaveFile(string url, string filename, string path)
        {
            SaveFile(url, filename, path, null, out var res);
            return res;
        }
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="url">文件下载地址</param>
        /// <param name="filename">文件名称</param>
        /// <param name="path">文件保存路径</param>
        /// <param name="Referrer">目标来源网页</param>
        /// <param name="status">文件下载结果</param>
        internal static void SaveFile(string url, string filename, string path, string Referrer, out string result)
        {
            int CycleRetry = 3;//失败重试次数
            int ErrorCount = 0;
        cc:
            result = "Success";
            HttpRequestMessage httpRequestMessage = new HttpRequestMessage
            {
                RequestUri = new Uri(url),
                Method = HttpMethod.Get
            };
            if (!string.IsNullOrEmpty(Referrer))
            {
                //伪装请求,绕过防盗链
                httpRequestMessage.Headers.Referrer = new Uri(Referrer);
            }

            HttpClientHandler httpClientHandler = new HttpClientHandler
            {
                //允许SSL
                ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true
            };
            HttpClient httpClient = new HttpClient(httpClientHandler);


            var httpResponse = httpClient.SendAsync(httpRequestMessage);
            string[] chars = { "<", ">", "/", "\\", "|", ":", "*", "?", "\"" };
            foreach (var item in chars)
            {
                filename = filename.Replace(item, "");
            }

            string filePath = $"{Environment.CurrentDirectory}/download/{path}/{filename}.jpg";

            if (!File.Exists(filePath))
            {
                try
                {
                    string folder = Path.GetDirectoryName(filePath);
                    if (!string.IsNullOrWhiteSpace(folder))
                    {
                        if (!Directory.Exists(folder))
                        {
                            Directory.CreateDirectory(folder);
                        }
                    }

                    File.WriteAllBytes(filePath, httpResponse.Result.Content.ReadAsByteArrayAsync().Result);
                }
                catch (Exception ex)
                {
                    if (ErrorCount < CycleRetry)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        ErrorCount++;
                        Console.WriteLine($"{filename}下载出错：{ex.Message}，第{ErrorCount}次重试...");
                        goto cc;
                    }
                    else
                    {
                        Console.ForegroundColor = ConsoleColor.White;
                        result = "Error";
                    }
                }
                Console.ForegroundColor = ConsoleColor.White;
            }
            httpClient.Dispose();
        }

        /// <summary>
        /// 获取html页面
        /// </summary>
        /// <param name="requestUrl">url地址</param>
        /// <returns></returns>
        internal static async Task<string> HtmlRequest(string requestUrl)
        {
            HttpClientHandler httpClientHandler = new HttpClientHandler
            {
                //允许SSL
                ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true
            };
            HttpClient httpClient = new HttpClient(httpClientHandler);
            httpClient.DefaultRequestHeaders.Add("Method", "Get");
            httpClient.DefaultRequestHeaders.Add("Method", "Get");
            httpClient.DefaultRequestHeaders.Add("KeepAlive", "false");   // HTTP KeepAlive设为false，防止HTTP连接保持
            httpClient.DefaultRequestHeaders.Add("UserAgent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
            var response = await httpClient.GetStringAsync(requestUrl);
            return response;
        }
    }
}
